package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisConstant;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.Address;
import com.itheima.pojo.CheckGroup;
import com.itheima.service.AddressService;
import com.itheima.utils.QiniuUtils;
import net.sf.jasperreports.engine.*;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.*;

@RestController
@RequestMapping("/address")
public class AddressController {
    @Autowired
    private JedisPool jedisPool;
    @Reference
    private AddressService addressService;

    /**
     * 添加操作
     * @return
     */
    @RequestMapping("/add")
    public Result add(@RequestBody Address address){
        try {
            addressService.add(address);
        }catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.ADD_ADDRESS_FAIL);
        }
        return new Result(true, MessageConstant.ADD_ADDRESS_SUCCESS);
    }

    /**
     * 分页操作
     * @param queryPageBean
     * @return
     */
    @RequestMapping("/findPage")
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean){
        return addressService.findPage(queryPageBean);
    }

    /**
     * 上传图片
     * @param imgFile
     * @return
     */
    @RequestMapping("/upload")
    public Result upload(MultipartFile imgFile){
        Jedis resource = null;
        try {
            resource = jedisPool.getResource();
            //获取后缀名
            int index = imgFile.getOriginalFilename().lastIndexOf(".");
            String extention = imgFile.getOriginalFilename().substring(index);
            //用UUID给图片起名
            String fileName = UUID.randomUUID().toString()+extention;
            QiniuUtils.upload2Qiniu(imgFile.getBytes(),fileName);
            resource.sadd(RedisConstant.SETMEAL_PIC_RESOURCES,fileName);
            return new Result(true, MessageConstant.PIC_UPLOAD_SUCCESS,fileName);
        } catch (IOException e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.PIC_UPLOAD_FAIL);
        }finally {
            if(resource!=null){
                resource.close();
            }
        }
    }

    /**
     * 编辑操作,数据回显
     * @return
     */
    @RequestMapping("/findById")
    public Result findById(Integer id){
        try {
            Address address=addressService.findById(id);
            return new Result(true, MessageConstant.QUERY_CHECKGROUP_SUCCESS,address);
        }catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.QUERY_CHECKGROUP_FAIL);
        }
    }

    /**
     * 编辑操作
     * @return
     */
    @RequestMapping("/edit")
    public Result edit(@RequestBody Address address1){
        try {
            addressService.update(address1);
            return new Result(true, MessageConstant.EDIT_ADDRESS_SUCCESS);
        }catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.EDIT_ADDRESS_FAIL);
        }
    }

    /**
     * 删除功能
     * @return
     */
    @RequestMapping("/delete")
    public Result delete(Integer id){
        try {
            addressService.delete(id);
            return new Result(true, MessageConstant.DELETE_ADDRESS_SUCCESS);
        } catch (RuntimeException e) {
            return new Result(false, e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.DELETE_ADDRESS_FAIL);
        }
    }

    /**
     * 批量导出PDF
     */
    @RequestMapping("/exportAddressPDF")
    public Result exportAddressPDF(Integer[] ids, HttpServletRequest request, HttpServletResponse response){
        List<Address> all = addressService.findByIds(ids);
        List<Map> list = new ArrayList<>();

        //伪造数据
        Map paramters = new HashMap();
        paramters.put("company", "传智播客");
        //将数据填充进map
        for (Address address : all) {
            Map<String, String> map = new HashMap<>();
            String name = address.getName();
            map.put("name", name);
            String phone = address.getPhone();
            map.put("phone", phone);
            String lng = address.getLng();
            map.put("lng", lng);
            String lat = address.getLat();
            map.put("lat", lat);
            String address1 = address.getAddress();
            map.put("address", address1);
            String img = address.getImg();
            map.put("img", img);
            list.add(map);
        }
        String jrxmlPath = request.getSession().getServletContext().getRealPath("template") + File.separator + "addressReportPDF.jrxml";
        String jasperPath = request.getSession().getServletContext().getRealPath("template") + File.separator + "addressReportPDF.jasper";
        try {
            JasperCompileManager.compileReportToFile(jrxmlPath, jasperPath);
        } catch (JRException e) {
            e.printStackTrace();
        }

        //填充数据---使用JavaBean数据源方式填充
        JasperPrint jasperPrint = null;
        try {
            jasperPrint = JasperFillManager.fillReport(jasperPath, paramters, new JRBeanCollectionDataSource(list));
            ServletOutputStream out = response.getOutputStream();
            response.setContentType("application/pdf");
            response.setHeader("content-Disposition", "attachment;filename=report.pdf");
            JasperExportManager.exportReportToPdfStream(jasperPrint, out);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @RequestMapping("/getAddressEcharts")
    public Result getAddressEcharts(){
        List<Map<String, Object>> list = addressService.findCityCount();
        Map<String, Object> map = new HashMap<>();
        map.put("data",list);
        return new Result(true,"哈哈哈",map);
    }
}
